package com.qiankan.qmsj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.qiankan.qmsj.MainActivity;
import com.qiankan.qmsj.R;
import com.qiankan.qmsj.UserInfo;
import com.qiankan.qmsj.activity.BaseActivity;
import com.qiankan.qmsj.activity.LogInActivity;
import com.qiankan.qmsj.activity.PersionInfoActivity;
import com.qiankan.qmsj.activity.ProductDetailActivity;
import com.qiankan.qmsj.activity.WebActivity;
import com.qiankan.qmsj.adapter.CommonAdapter;
import com.qiankan.qmsj.db.UserDBHelper;
import com.qiankan.qmsj.entity.Banner;
import com.qiankan.qmsj.entity.Labels;
import com.qiankan.qmsj.entity.MainFragmentEntity;
import com.qiankan.qmsj.entity.Product;
import com.qiankan.qmsj.entity.Result;
import com.qiankan.qmsj.event.TypeEvent;
import com.qiankan.qmsj.net.APIHub;
import com.qiankan.qmsj.utils.AsyncLoadImage;
import com.qiankan.qmsj.viewHolder.CommonViewHolder;
import com.qiankan.qmsj.viewHolder.HotTopicViewHolder;
import com.qiankan.qmsj.viewHolder.ProductViewHolder;
import com.qiankan.qmsj.widget.TipToast;
import com.qiankan.qmsj.widget.bannerViewPager.BannerViewPager;
import com.qiankan.qmsj.widget.bannerViewPager.OnPageClickListener;
import com.qiankan.qmsj.widget.bannerViewPager.ViewPagerAdapter;
import com.xingchen.AlertDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/8/14.
 */

public class MainFragment extends BaseFragment {
    @BindView(R.id.banner)
    BannerViewPager bannerViewPager;
    @BindView(R.id.rv_loanRecommend)
    RecyclerView loanRecommend;
    @BindView(R.id.rv_hotTopic)
    RecyclerView hotTopic;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefreshLayout;
    private ViewPagerAdapter bannerAdapter;
    private CommonAdapter<Product> productRecommendAdapter;
    private CommonAdapter<Product> hotTopicAdapter;
    private List<ImageView> mBanners = new ArrayList<>();
    private List<Product> loanRecommendList = new ArrayList<>();// 贷款推荐集合
    private List<Product> hotTopicList = new ArrayList<>();// 热门活动
    private MainFragmentEntity mainFragmentData;

    @Override
    public int getContentViewId() {
        return R.layout.main_fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
        initView();
        initListener();
        ((BaseActivity) getActivity()).showLoadingDialog();
        refresh();
    }

    private void init() {
        loanRecommend.setHasFixedSize(true);
        loanRecommend.setNestedScrollingEnabled(false);
        loanRecommend.setLayoutManager(new LinearLayoutManager(getActivity()));
//        loanRecommend.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
        hotTopic.setHasFixedSize(true);
        hotTopic.setNestedScrollingEnabled(false);
        hotTopic.setLayoutManager(new LinearLayoutManager(getActivity()));
        initBanner();
        initLoanRecommend();
        initHotTopic();
    }

    private void initView() {
        initBannerView();
        initLoanRecommendView();
        initHotTopicView();
    }

    private void initBanner() {
        for (int i = 0; i < 5; i++) {
            ImageView iv = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.banner_item, null);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            AsyncLoadImage.loadImage("", iv, R.mipmap.banner_def);
            mBanners.add(iv);
        }
        bannerAdapter = new ViewPagerAdapter(mBanners, new OnPageClickListener() {
            @Override
            public void onPageClick(View view, int position) {
                MobclickAgent.onEvent(getActivity(), "buttom_banner" + (position + 1));
                UserInfo userInfo = UserDBHelper.getInstance(getActivity()).getUserInfo();
                if (userInfo == null) {
                    Intent intent = new Intent(getActivity(), LogInActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    return;
                }
                if (TextUtils.isEmpty(userInfo.getName()) || TextUtils.isEmpty(userInfo.getIdcard()) || TextUtils.isEmpty(userInfo.getPhone())) {
                    showDialog();
                    return;
                }
                Bundle bundle = new Bundle();
                Banner banner = mainFragmentData.getUpbanners().get(position);
                bundle.putString("url", mainFragmentData.getUpbanners().get(position).getLink());
                //分享相关
                bundle.putString("shareUrl", banner.getLink());
                bundle.putString("title", "荣耀钱包");
                bundle.putString("content", "");
                bundle.putString("sharePicUrl", banner.getPath());
                startActivity(WebActivity.newIntent(getActivity(), bundle));
            }
        });
        bannerViewPager.setAdapter(bannerAdapter);
    }

    private void initLoanRecommend() {
        productRecommendAdapter = new CommonAdapter<Product>(getActivity(), ProductViewHolder.class, loanRecommendList, R.layout.product_recommend_item) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, final Product item, int position) {
                ProductViewHolder viewHolder = (ProductViewHolder) holder;
                AsyncLoadImage.loadImage(item.getIcon(), viewHolder.mProductLogo, R.mipmap.ic_launcher);
                viewHolder.mProductName.setText(item.getName());
                viewHolder.mMaxMoney.setText(item.getMaxmoney());
                viewHolder.mAdvertisement.setText(item.getAdvertising());
                viewHolder.mDayRate.setText(String.format("日费率%1$s%%", item.getDayRate()));
                viewHolder.mLoanTime.setText(String.format("贷款期限%1$s-%2$s天", item.getMintime(), item.getMaxtime()));
                viewHolder.mLabelRoot.removeAllViews();
                for (Labels label : item.getLabels()) {
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.setMargins(10, 0, 0, 0);
                    TextView textView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.text_label_layout, null);
                    textView.setText(label.getName());
                    textView.setLayoutParams(lp);
                    viewHolder.mLabelRoot.addView(textView);
                }
                viewHolder.setOnRecyclerViewListener(new CommonViewHolder.OnRecyclerViewListener() {
                    @Override
                    public void onItemClick(View view) {
                        Intent intent = ProductDetailActivity.newIntent(getActivity(), item);
                        startActivity(intent);
                    }
                });
            }
        };
        loanRecommend.setAdapter(productRecommendAdapter);
    }

    private void initHotTopic() {
        hotTopicAdapter = new CommonAdapter<Product>(getActivity(), HotTopicViewHolder.class, hotTopicList, R.layout.special_item) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, final Product item, final int position) {
                HotTopicViewHolder viewHolder = (HotTopicViewHolder) holder;
                AsyncLoadImage.loadImage(item.getIcon(), viewHolder.mHotTopicImg);
                viewHolder.mHotTopicNameTv.setText(item.getName());
                viewHolder.mHotTopicIntroTv.setText(item.getRemark());
                viewHolder.setOnRecyclerViewListener(new CommonViewHolder.OnRecyclerViewListener() {
                    @Override
                    public void onItemClick(View view) {
                        ((MainActivity) getActivity()).setCurrentTab(1);
                        EventBus.getDefault().post(new TypeEvent(item.getId()));
                    }
                });
            }
        };
        hotTopic.setAdapter(hotTopicAdapter);
    }

    private void initListener() {
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refresh();
            }
        });
    }

    private void refresh() {
        APIHub.getsInstance().getBaseService().getMainFragmentData().enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                smartRefreshLayout.finishRefresh();
                ((BaseActivity) getActivity()).dismissLoadingDialog();
                Result result = response.body();
                if (result != null && result.getCode().equals("200")) {
                    mainFragmentData = new Gson().fromJson(result.getData(), MainFragmentEntity.class);
                    initView();
                } else {
                    TipToast.toast(getActivity(), result.getRemark());
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                smartRefreshLayout.finishRefresh();
                TipToast.toast(getActivity(), "网络连接失败");
                ((BaseActivity) getActivity()).dismissLoadingDialog();
            }
        });
    }

    @OnClick(R.id.tv_moreRecommend)
    public void onClickMore(View view) {
        ((MainActivity) getActivity()).setCurrentTab(1);
        EventBus.getDefault().post(new TypeEvent(""));
    }

    private void initLoanRecommendView() {
        if (mainFragmentData != null && mainFragmentData.getProducts().size() > 0) {
            loanRecommendList.clear();
            loanRecommendList.addAll(mainFragmentData.getProducts());
            productRecommendAdapter.notifyDataSetChanged();
        }
    }

    private void initHotTopicView() {
        if (mainFragmentData != null && mainFragmentData.getActivity().size() > 0) {
            hotTopicList.clear();
            hotTopicList.addAll(mainFragmentData.getFixtype());
            hotTopicAdapter.notifyDataSetChanged();
        }
    }

    private void initBannerView() {
        if (mainFragmentData != null && mainFragmentData.getUpbanners().size() > 0) {
            mBanners.clear();
            for (Banner upBanner : mainFragmentData.getUpbanners()) {
                ImageView iv = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.banner_item, null);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                AsyncLoadImage.loadImage(upBanner.getPath(), iv, R.mipmap.banner_def);
                mBanners.add(iv);
                bannerAdapter.notifyDataSetChanged();
            }
        }
    }

    @OnClick(R.id.rl_cash)
    public void onClickCash(View view) {
        ((MainActivity) getActivity()).setCurrentTab(1);
        EventBus.getDefault().post(new TypeEvent(mainFragmentData.getMaintype().get(0).getId()));
    }

    @OnClick(R.id.rl_recommend)
    public void onClickRecommend(View view) {
        ((MainActivity) getActivity()).setCurrentTab(1);
        EventBus.getDefault().post(new TypeEvent(mainFragmentData.getMaintype().get(1).getId()));
    }

    private void showDialog() {
        new AlertDialog(getActivity()).builder().setTitle("提示")
                .setMsg("请完善个人信息 ")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(PersionInfoActivity.newIntent(getActivity()));
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }).show();
    }
}
